using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using mapshiftApplication.Dto;
using mapshiftApplication.Services;

namespace mapshiftApplication.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TsmcConfigController : ControllerBase
    {
        private readonly TsmcConfigService _tsmcConfigService;

        public TsmcConfigController(TsmcConfigService tsmcConfigService)
        {
            _tsmcConfigService = tsmcConfigService;
        }

        [HttpGet("query")]
        public async Task<ActionResult<IEnumerable<TsmcConfigDto>>> QueryTsmcConfigs([FromQuery] int page, [FromQuery] int pageSize)
        {
            // 前端发送 pageSize 99999 表示希望获取所有数据进行前端分页和筛选
            var configs = await _tsmcConfigService.GetAllTsmcConfigsAsync();
            return Ok(configs);
        }

        [HttpPost("create")]
        public async Task<ActionResult<TsmcConfigDto>> CreateTsmcConfig([FromBody] TsmcConfigDto config)
        {
            var newConfigId = await _tsmcConfigService.CreateTsmcConfigAsync(config);
            config.Id = newConfigId;
            return CreatedAtAction(nameof(GetTsmcConfigById), new { id = newConfigId }, config);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<TsmcConfigDto>> GetTsmcConfigById(string id)
        {
            var config = await _tsmcConfigService.GetTsmcConfigByIdAsync(id);
            if (config == null)
            {
                return NotFound();
            }
            return Ok(config);
        }

        [HttpPut("update/{id}")]
        public async Task<ActionResult> UpdateTsmcConfig(string id, [FromBody] TsmcConfigDto config)
        {
            if (id != config.Id)
            {
                return BadRequest("ID mismatch");
            }

            var rowsAffected = await _tsmcConfigService.UpdateTsmcConfigAsync(config);
            if (rowsAffected == 0)
            {
                return NotFound();
            }
            return NoContent();
        }

        [HttpDelete("delete/{id}")]
        public async Task<ActionResult> DeleteTsmcConfig(string id)
        {
            var rowsAffected = await _tsmcConfigService.DeleteTsmcConfigAsync(id);
            if (rowsAffected == 0)
            {
                return NotFound();
            }
            return NoContent();
        }
    }
}
